import threading
import subprocess
import time
from queue import Queue
import os
import sys
import datetime
import re

# 获取当前系统：linux / windows
res_test_win = subprocess.call('dir', shell=True)
is_windows = True if res_test_win == 0 else False
# ping操作符 win: '-n' ,linux: '-c'
operation_ip = '-n' if is_windows else '-c'
# arp操作符 win：'-a' ,linux '-n'
operation_arp = '-a' if is_windows else '-n'

# 定义工作线程
WORD_THREAD = 50

# 将需要 ping 的 ip 加入队列
IP_QUEUE = Queue()
for i in range(1, 255):
    IP_QUEUE.put('192.168.0.'+str(i))

# 获取当前地址
path =os.path.dirname(__file__)
# 配置log文件夹
logsdir = path+"/logs/"
if not os.path.exists(logsdir):
    os.makedirs(logsdir)
# 创建日志文件
file = logsdir+"/"+str(datetime.date.today())+" "+str(os.getpid())+".log"

f = open(file, 'a')

# 正则匹配mac地址
mac_pattern = "([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}"

li = list()

# 定义一个执行 ping 的函数


def ping_ip():
    # 当前工作目录
    # softwarename=sys.argv[0].rsplit('/',1)[0].split(".")[1]
    # logsdir=prepath+"logs/"+str(datetime.datetime.now()).replace(':',"-")
    # path=os.makedirs(logsdir) if not os.path.exists(logsdir) else logsdir

    while not IP_QUEUE.empty():
        ip = IP_QUEUE.get()


        res = subprocess.call('ping %s 2 -w 5 %s' %
                              (operation_ip, ip), stdout=subprocess.PIPE)

        # 打印运行结果
        b = True if res == 0 else False
        a = "------success" if b else ""
        c = ""

        # 如果执行成功则打印mac
        if (b):
            resarp = subprocess.Popen('arp %s %s' % (
                operation_arp, ip), shell=True, stdout=subprocess.PIPE)
            strc = resarp.stdout.read().decode('gbk')
            re_c=re.search(mac_pattern, strc)
            if(re_c is not None):
                c = re_c.group(0)
                c = "  mac="+c
                
                

            f.writelines(ip+a+c+"\n")

        li.append((ip, b))


if __name__ == '__main__':

    threads = []
    start_time = time.time()
    # 启动线程
    for i in range(WORD_THREAD):
        thread = threading.Thread(target=ping_ip)
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()

    info = 'catch time:%s' % (time.time() - start_time)
    f.writelines(info)
    print(info)
    li.sort()
    for i in li:
        print(i)

    f.close()
